﻿using ICPFrameLib.Business;
using ICPFrameLib.Attributes;
using XHRPMIS.Common;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Base.Data.Base;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using EFFC.Frame.Net.Unit.DB.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Unit.DB;
using EFFC.Frame.Net.Base.Data;
using System.IO;
using EFFC.Frame.Net.Base.Constants;
using System.Text.RegularExpressions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System.Text;
using ICPFrameLib.Common;
using EFFC.Frame.Net.Unit.DB.Datas;

namespace XHRPMIS.Business.v1._0
{
    public partial class MetaDynamicForm
    {
        #region OpenAPI
        [EWRARouteDesc("获取虚拟栏位的计算结果")]
        [EWRARoute("post", "/md_form/virsual/{id}")]
        [EWRAAddInput("limit", "int", "每页笔数，当mode为Normal时需要提供", "默认为10", EFFC.Frame.Net.Base.Constants.RestInputPosition.QueryString, true)]
        [EWRAAddInput("page", "int", "指定页数，当mode为Normal时需要提供", "默认为1", EFFC.Frame.Net.Base.Constants.RestInputPosition.QueryString, true)]
        [EWRAAddInput("is_filter_deleted", "bool", "是否过滤掉逻辑删除的资料", "默认为true", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("id", "string", "元数据表的uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("column_name", "string", "指定栏位的名称，多个用逗号分隔", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("this_data", "string", @"页面上当前编辑的行资料，先采用url编码，再采用base64编码，原数据格式:
{
    column_name1:'值，如果为file、picture类型则值的格式内容为上传后的文件路径',
    column_name2:'值，如果为file、picture类型则值的格式内容为上传后的文件路径',
    .....
    column_nameN:'值，如果为file、picture类型则值的格式内容为上传后的文件路径',
}", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("ref_data", "string", @"页面上当前编辑的行资料的父节点资料，先采用url编码，再采用base64编码，原数据格式:
{
    column_name1:'值，如果为file、picture类型则值的格式内容为上传后的文件路径',
    column_name2:'值，如果为file、picture类型则值的格式内容为上传后的文件路径',
    .....
    column_nameN:'值，如果为file、picture类型则值的格式内容为上传后的文件路径',
}", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAOutputDesc("返回结果", @"如果是授权无效的情况下，返回400错，其它情况的返回结果集（状态为200）如下：{
code:'success-成功，failed-失败',
msg:'提示信息',
column_value:'表示选中值的栏位名称,如果为空，则表示接受UI设定的任意值',
column_show:[{
    column_name:'栏位名称',
    column_desc:'栏位中文名称',
    ui_type:'UI控件类型'
}],
data:{
    v_column1:{
        total_count:'总笔数',
        page:'当前页数',
        total_page:'总页数',
        limit:'每页笔数',
        data:[结果集],
    }
    v_column2:{
        total_count:'总笔数',
        page:'当前页数',
        total_page:'总页数',
        limit:'每页笔数',
        data:[结果集],
    },
    ......
    v_columnN:{
        total_count:'总笔数',
        page:'当前页数',
        total_page:'总页数',
        limit:'每页笔数',
        data:[结果集],
    }
}   
}")]
        object GetVirsualCal(string id)
        {
            string fixed_orderby_express = ComFunc.UrlDecode(ComFunc.IsBase64Then(PostDataD.fixed_orderby_express));
            string[] column_names = ComFunc.nvl(PostDataD.column_name).Split(",",StringSplitOptions.RemoveEmptyEntries);
            var is_filter_deleted = BoolStd.IsNotBoolThen(PostDataD.is_filter_deleted, true);

            SetCacheEnable(false);
            var metaup = DB.NewMetaUnitParameter();
            var up = DB.NewDBUnitParameter();
            var tableinfo = MetaDataUtilities.GetAllTables( metaup).Where(w => (w.MetaUID == id || w.MetaName == id)).FirstOrDefault();
            if(tableinfo == null)
            {
                return new
                {
                    code = "failed",
                    msg = "元数据不存在，无法继续进行操作"
                };
            }
            
            var metainfolist = tableinfo.columns.Where(w => column_names.Contains(w.MetaColumnName) && w.IsVirsual);
            if (metainfolist.Count() <= 0)
            {
                return new
                {
                    code = "failed",
                    msg = "相关栏位资料不存在，无法继续进行操作"
                };
            }
            FrameDLRObject rtndata = FrameDLRObject.CreateInstance(FrameDLRFlags.SensitiveCase);
            foreach (var metainfo in metainfolist)
            {
                var data_type = ComFunc.nvl(metainfo.MetaDataType);
                var column_cal = ComFunc.nvl(metainfo.CalExpress);
                if (column_cal == "")
                {
                    return new
                    {
                        code = "failed",
                        msg = "相关栏位缺少计算信息，无法继续进行操作"
                    };
                }
                var calResult = CalExpress.ParseExpress(column_cal);
                if (calResult == null)
                {
                    return new
                    {
                        code = "failed",
                        msg = "相关栏位关联信息描述存在错误，无法继续进行操作"
                    };
                }
                if (calResult.Mode == CalExpress.CalMode.Normal)
                {
                    var data_str = ComFunc.nvl(PostDataD.this_data).Replace(" ", "+");
                    var this_data_base64str = ComFunc.IsBase64Then(data_str);
                    string this_data_str = ComFunc.UrlDecode(this_data_base64str);
                    var this_data = FrameDLRObject.IsJsonThen(this_data_str);
                    if (data_str != "" && (this_data_str == "" || this_data == null))
                    {
                        return new
                        {
                            code = "failed",
                            msg = "当前行资料格式不正确"
                        };
                    }
                    var ref_data_str = ComFunc.nvl(PostDataD.ref_data).Replace(" ", "+");
                    var ref_this_data_base64str = ComFunc.IsBase64Then(ref_data_str);
                    string ref_this_data_str = ComFunc.UrlDecode(ref_this_data_base64str);
                    var ref_data = FrameDLRObject.IsJsonThen(ref_this_data_str);
                    if (ref_data_str != "" && (ref_this_data_str == "" || ref_data == null))
                    {
                        return new
                        {
                            code = "failed",
                            msg = "父节点资料格式不正确"
                        };
                    }
                    var data = new List<FrameDLRObject>();
                    UnitDataCollection result = null;
                    //树结构表达式条件过滤
                    Func<string, string, bool, object, object[]> tree_func = (cur_table, column, is_parent_column, value) =>
                    {
                        return RefExpreeTreeIn(up, metaup, cur_table, column, value, is_parent_column);
                    };
                    var dbexpress = calResult.ToDBExpress(this_data, false, ref_data, false, tree_func);
                    var tablename = ComFunc.nvl(dbexpress.GetValue("$table"));
                    var targetinfo = MetaDataUtilities.GetAllTables( metaup).Where(w => w.MetaName == tablename).FirstOrDefault();
                    if (targetinfo == null)
                    {
                        return new
                        {
                            code = "failed",
                            msg = "无表达式中指定的数据对象新增，操作终止"
                        };
                    }
                    //过滤逻辑删除的资料
                    if (is_filter_deleted && !tablename.ToUpper().StartsWith("COMMON_"))
                    {
                        FrameDLRObject where = dbexpress.GetValue("$where") == null ? FrameDLRObject.CreateInstance(FrameDLRFlags.SensitiveCase) : (FrameDLRObject)dbexpress.GetValue("$where");
                        where.SetValue("_is_deleted", 0);
                    }

                    dbexpress.SetValue("$acttype", "QueryByPage");

                    result = DB.Excute(up, dbexpress, true);
                    data = result.QueryData<FrameDLRObject>();

                    SetRefColumnsText(metaup, up, targetinfo, targetinfo.columns.Where(w => !w.IsVirsual && calResult.GroupBy.Contains(w.MetaColumnName)).ToList(), data, is_filter_deleted);

                    rtndata.SetValue(metainfo.MetaColumnName, new
                    {
                        total_count = result.TotalRow,
                        page = result.CurrentPage,
                        total_page = result.TotalPage,
                        limit = result.Count_Of_OnePage,
                        data
                    });
                }
                else
                {
                    var hjs = calResult.ToHostJs();
                    var re = HostScript.GetHostLogicEngine().RunFormatJs(hjs);
                    rtndata.SetValue(metainfo.MetaColumnName, re);
                }
            }

            return new
            {
                code = "success",
                msg = "",
                data = rtndata
            };
        }

        #endregion

        #region LocalFunction

        #endregion


    }
}
